<?php

namespace App\Http\Middleware;

use Closure;
use App\Models\WorkUser;
use App\Models\UserToken;
use App\Traits\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CheckWorkUser
{
    use ApiResponse;

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $token = $request->bearerToken();
        
        if (!$token) {
            return $this->unauthorized('Token not provided');
        }

        $workUser = WorkUser::where('token', $token)->where('expired_at', '>', now())->first();

        if (!$workUser instanceof WorkUser) {
            return $this->unauthorized('Invalid or expired token');
        }

        $request->attributes->add(['work_user' => $workUser]);

        return $next($request);
    }
}
